import React from 'react';
import { Tag, Select, message } from 'antd';
import { TweenOneGroup } from 'rc-tween-one';
import { PlusOutlined } from '@ant-design/icons';
import { getAllEngineers } from '@/services/mockApi/peopleManage';
import { updateDevice } from '@/services/mockApi/deviceManage';

/**
 * 卡编辑标签组件
 * @description 直接从 antd 官网拷贝来的，就不大改动了
 */
class EditableTagGroup extends React.Component {
  constructor(props) {
    super(props);
    // console.log('info', props);
    // todo : tags的label和value都得保存
    this.state = {
      tags: this.props?.deviceInfo?.engineers?.map((item) => item.value) || [],
      deviceInfo: this.props.deviceInfo,
      selectVisible: false,
      selectValue: '',
      selectOptions: [],
    };
  }

  componentDidMount() {
    // 获取相关数据
    getAllEngineers()
      .then((res) => {
        const engineers = res.data.map((item) => {
          return {
            label: item.realName,
            value: item.realName,
          };
        });
        // console.log('engineers', engineers);
        this.setState({ selectOptions: engineers });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  handleClose = (removedTag) => {
    const tags = this.state.tags.filter((tag) => tag !== removedTag);
    console.log(tags);
    this.setState({ tags });
  };

  showSelect = () => {
    this.setState({ selectVisible: true }, () => this.select.focus());
  };

  handleSelectChange = (value) => {
    this.setState({ selectValue: value });
  };

  handleSelectConfirm = () => {
    const { selectValue } = this.state;
    let { tags } = this.state;
    if (selectValue && tags.indexOf(selectValue) === -1) {
      tags = [...tags, selectValue];
    }
    // 新的设备信息数据
    let newDeviceInfo = this.state.deviceInfo;
    // 如果不为空，则发起请求
    if (selectValue) {
      newDeviceInfo = {
        ...this.state.deviceInfo,
        engineers: tags.map((item) => {
          return { label: item, value: item };
        }),
      };
      updateDevice({
        ...newDeviceInfo,
      })
        .then((res) => {
          message.success('添加负责工程师成功!');
        })
        .catch((err) => {
          console.log(err);
          message.error('添加负责工程师失败!');
        });
    }
    this.setState({
      tags,
      selectVisible: false,
      selectValue: '',
      deviceInfo: selectValue ? newDeviceInfo : this.state.deviceInfo,
    });
  };

  saveSelectRef = (select) => {
    this.select = select;
  };

  forMap = (tag) => {
    const tagElem = (
      <Tag
        closable
        onClose={(e) => {
          e.preventDefault();
          this.handleClose(tag);
        }}
      >
        {tag}
      </Tag>
    );
    return (
      <span key={tag} style={{ display: 'inline-block' }}>
        {tagElem}
      </span>
    );
  };

  render() {
    const { tags, selectVisible, selectValue } = this.state;
    const tagChild = tags.map(this.forMap);
    return (
      <>
        <div style={{ marginBottom: 16 }}>
          <TweenOneGroup
            enter={{
              scale: 0.8,
              opacity: 0,
              type: 'from',
              duration: 100,
            }}
            onEnd={(e) => {
              if (e.type === 'appear' || e.type === 'enter') {
                e.target.style = 'display: inline-block';
              }
            }}
            leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
            appear={false}
          >
            {tagChild}
          </TweenOneGroup>
        </div>
        {selectVisible && (
          <Select
            ref={this.saveSelectRef}
            type="text"
            size="small"
            style={{ width: '88px' }}
            value={selectValue}
            options={this.state.selectOptions}
            onChange={this.handleSelectChange}
            onBlur={this.handleSelectConfirm}
          />
        )}
        {!selectVisible && (
          <Tag
            onClick={this.showSelect}
            // className="site-tag-plus"
            style={{ width: '88px', background: '#fff', borderStyle: 'dashed' }}
          >
            <PlusOutlined /> New Tag
          </Tag>
        )}
      </>
    );
  }
}

export default EditableTagGroup;
